using System.IO;
using System.Text;
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEngine;

#if UNITY_IPHONE
using UnityEditor.iOS.Xcode;
#endif

namespace GameMain.Editor.BuildPipeline
{
    public partial class BuildPipeline
    {
#if UNITY_IPHONE
        [PostProcessBuild(88)]
        public static void OnPostProcessBuild(BuildTarget target, string targetPath)
        {
            if (target != BuildTarget.iOS)
            {
                Debug.LogWarning("[BuildPipeline::OnPostProcessBuild]" +
                                 "Target is not iPhone. XCodePostProcess will not run");
                return;
            }

            var projPath = Path.GetFullPath(targetPath) + "/Unity-iPhone.xcodeproj/project.pbxproj";

            var proj = new PBXProject();
            proj.ReadFromFile(projPath);

            var targetGuid = proj.GetUnityFrameworkTargetGuid();

            var shellName = "PreBuildIl2CPP";
            var shellPath = "";
            var sbShellScript = new StringBuilder();
            sbShellScript.AppendLine("echo PreBuildIl2CPP Start");
            sbShellScript.AppendLine("cd ../HybridCLRData/iosBuild/");
            sbShellScript.AppendLine("sh build_libil2cpp.sh");
            sbShellScript.AppendLine("cp build/libil2cpp.a $PROJECT_DIR/Libraries/libil2cpp.a");
            sbShellScript.AppendLine("echo PreBuildIl2CPP Finished");
            var sGuid = proj.InsertShellScriptBuildPhase(0, targetGuid, shellName, shellPath, sbShellScript.ToString());
            Debug.Log($"[BuildPipeline::OnPostProcessBuild] AddShellScriptBuildPhase:{sGuid}");

            proj.WriteToFile(projPath);
        }
#endif
    }
}
